﻿using CHSystemApi.DataAccess.Entities;
using CHSystemApi.Framework.DataAccess;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CHSystemApi.Business.implement
{
    public class PermissionBusiness : IPermissionBusiness
    {
        IDataAccess _dataAccess { get; }
        public PermissionBusiness(IDataAccess dataAccess)
        {
            _dataAccess = dataAccess;
        }

        public bool AddPermission(Permission permission)
        {
           var res = _dataAccess.Context.Permission.Add(permission);
            return true;
        }

        public bool AddPermissions(Permission[] permissions)
        {
            throw new NotImplementedException();
        }

        public Permission[] GetPermission(int id)
        {
            throw new NotImplementedException();
        }

        public Permission[] GetPermissions()
        {
            return _dataAccess.Context.Permission.ToArray();
        }

        public Permission[] GetPermissionsByUserid(int userid)
        {
            return _dataAccess.Context.Set<Permission>().FromSqlRaw(@"
                SELECT
	                P.*
                FROM
	                permissionassignment AS PALL
	                LEFT JOIN permission AS P ON PALL.pid = P.id 
                WHERE
	                PALL.uid = 1 
	                AND PALL.type = 0 UNION
                SELECT
	                P.*
                FROM
	                permissionassignment AS PALL
	                LEFT JOIN permissiongrouprule AS PG ON PALL.pid = PG.pgid
	                LEFT JOIN permission AS P ON PG.pid = P.id 
                WHERE
	                PALL.uid = 1 
	                AND PALL.type = 1
            ").ToArray();
        }

        public bool AddPermission()
        {
            throw new NotImplementedException();
        }
    }
}
